<template>
  <div class="userProfile-container card-shadow iScroll">
    <div class="avatar">
      <el-image :src="mainStore.userProfile?.avatar" fit="cover">
        <template #placeholder> 暂无头像 </template>
        <template #error> 头像获取失败 </template>
      </el-image>
      <input type="file" id="file-input" accept=".jpg,.jpeg,.png" style="display: none" />
      <div class="upload-avatar" @click.stop="toSelectAvatar">上传头像</div>
    </div>
    <div class="info iScroll">
      <el-form
        ref="formRef"
        :model="profile"
        :rules="formRule"
        label-position="top"
        label-width="110px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input disabled v-model="profile.username"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input :maxLength="15" v-model="profile.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input :maxLength="11" v-model="profile.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profile.email"></el-input>
        </el-form-item>
        <el-form-item label="上一次登录" prop="lastLogin">
          <el-input disabled v-model="profile.lastLogin"></el-input>
        </el-form-item>
        <el-form-item label="上一次登录IP" prop="lastLoginIp">
          <el-input disabled v-model="profile.lastLoginIp"></el-input>
        </el-form-item>
        <el-form-item label="上一次资料更新" prop="lastUpdate">
          <el-input disabled v-model="profile.lastUpdate"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input type="textarea" :rows="4" v-model="profile.introduction"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doUsersProfileUpdate(formRef)">提交资料</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { debounce } from '@/utils/throttleAndDebounce'
import { uploadAvatar, getUsersProfile, usersProfileUpdate } from '@/api/userProfile'
import { useMainStore } from '@/stores/mainStore'

let fileInput: HTMLInputElement

const mainStore = useMainStore()

const profile = ref<UserProfile>({
  id: 0,
  nickname: '',
  username: '',
  lastLogin: '',
  lastLoginIp: '',
  lastUpdate: '',
  status: '',
  introduction: '',
  avatar: '',
  phone: '',
  email: ''
})

function toGetUsersProfile() {
  getUsersProfile().then((res) => {
    if (res.code === 200) {
      profile.value = res.data!
      mainStore.userProfile!.avatar = profile.value?.avatar
    }
  })
}

onMounted(() => {
  fileInput = document.getElementById('file-input') as HTMLInputElement
  fileInput.addEventListener(
    'change',
    debounce(async function (e: Event) {
      const input = e.target as HTMLInputElement
      const files = input.files
      if (files && files.length === 1) {
        // 确保只处理一个文件
        const filesArr = fileInput.files ? Array.from(fileInput.files) : []
        await uploadAvatar(filesArr)
        toGetUsersProfile()
      }
    }, 1000)
  )
  toGetUsersProfile()
})

// 点击上传头像
function toSelectAvatar() {
  fileInput.value = ''
  fileInput.click()
}

const formRef = ref<FormInstance>()
const formRule = reactive<FormRules<typeof profile>>({
  id: { required: true },
  nickname: { required: true, message: '请输入昵称' },
  username: { required: true },
  lastLogin: { required: true },
  lastLoginIp: { required: true },
  lastUpdate: { required: true },
  status: { required: true },
  avatar: { required: true },
  phone: { required: true, message: '请输入手机号' }
})

// 提交资料
function doUsersProfileUpdate(form: FormInstance | undefined) {
  if (!form) return
  form.validate((vail: boolean) => {
    if (vail) {
      usersProfileUpdate(profile.value).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '修改成功'
          })
          toGetUsersProfile()
        }
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.userProfile-container {
  display: flex;
  height: calc(100% - 72px);
  width: calc(100% - 36px);
  padding: 36px;
  padding-right: 0;
  gap: 36px;
  overflow: hidden;
  overflow-x: scroll;

  .avatar {
    position: relative;
    min-width: 200px;
    max-width: 250px;
    max-height: fit-content;
    height: auto;
    :deep(.el-image) {
      aspect-ratio: 1 / 1;
      width: 100%;
      height: auto;
      padding: 0;
      margin: 0;
    }
    .upload-avatar {
      width: 100%;
      height: 40px;
      position: absolute;
      bottom: 5px;
      background-color: rgba(0, 0, 0, 0.2);
      color: white;
      font-size: 0.7em;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0;
      padding: 0;
      &:hover {
        background-color: rgba(0, 0, 0, 0.6);
        font-weight: 600;
        cursor: pointer;
      }
    }
  }
  .info {
    width: calc(100% - 500px);
    padding-right: 300px;
    min-width: 400px;
    height: 100%;
    overflow-y: scroll;
  }
}
</style>
